package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDto;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.query.UserQuery;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "用户管理接口")
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @PostMapping
    @ApiOperation("新增用户接口")
    public void saveUser(@RequestBody UserFormDTO userFormDTO) {
        //1.将dto转换成po 对象属性拷贝
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        //2.新增用户
        userService.save(user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户接口")
    public void deleteUser(@ApiParam("用户id") @PathVariable("id") Long id) {
        userService.removeById(id);
    }

    @GetMapping("/{id}")
    @ApiOperation("通过id查询用户接口")
    public UserVO getUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
        return userService.getUserAndAddresses(id);
    }

    @GetMapping
    @ApiOperation("通过id批量查询用户接口")
    public List<UserVO> getUserByIds(@ApiParam("用户id集合") @RequestParam("ids") List<Long> ids) {
        return userService.getUsersAndAddresses(ids);
    }

    @PutMapping("/{id}/deduction/{money}")
    @ApiOperation("通过id扣用户钱接口")
    public void deductBalance(@ApiParam("用户id") @PathVariable("id") Long id,
                              @ApiParam("扣除金额") @PathVariable("money") Integer money) {
        userService.deductBalance(id, money);
    }

    @GetMapping("/list")
    @ApiOperation("通过复杂条件批量查询用户接口")
    public List<UserVO> getUsers(UserQuery userQuery) {
        return userService.getUsers(userQuery.getName(), userQuery.getStatus(), userQuery.getMaxBalance(), userQuery.getMinBalance());
    }

    @GetMapping("/page")
    @ApiOperation("通过条件分页查询用户接口")
    public PageDto<UserVO> getUsersPage(UserQuery userQuery) {
        return userService.getUsersPage(userQuery);
    }
}
